<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :limit="1"
      :class="{ disabled: fileComputed }"
      :on-preview="preview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :http-request="upload"
      :on-change="changeFile"
      :file-list="fileList"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showPercent" :percentage="percent" style="width: 180px" />
    <el-dialog title="图片预览" :visible.sync="showDialog" width="50%">
      <img :src="imgUrl" alt="" style="width: 100%">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 引入腾讯云cos包
const cos = new COS({
  SecretId: 'AKIDHNDm45qLYWDcsqXx7zax5wXrviETSBdo',
  SecretKey: 'wbz80cx1UjiPpzsVrwlIYXFhsmOkoc9Q'
})

export default {
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: '',
      currentFileUid: null, // 记录当前正在上传的uid
      percent: 0,
      showPercent: false
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  methods: {
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    handleRemove(file, fileList) {
      // file是要删除的文件 ，fileList是删除之后的文件
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    changeFile(file, fileList) {
      // this.fileList = fileList.map(item => item)
      this.fileList = [...fileList] // 浅拷贝
    },
    beforeUpload(file) {
      const type = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!type.some(item => item === file.type)) {
        this.$message.error('上传图片只能是 JPG, GIF, BMP, PNG 格式')
        return false
      }

      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('上传的图片大小不能超过5M')
        return false
      }
      this.currentFileUid = file.uid
      this.showPercent = true
      return true
    },
    upload(params) {
      if (params.file) {
        cos.putObject({
          Bucket: 'people-resource-1308218543', // 存储桶名称
          Region: 'ap-shanghai', // 存储桶所在地域
          Key: params.file.name, // 文件名
          Body: params.file, // 要上传的文件对象
          StorageClass: 'STANDARD', // 上传的模式类型：默认标准模式
          onProgress: (params) => {
            this.percent = params.percent * 100
          }
        }, (err, data) => {
          console.log(err || data)
          if (!err && data.statusCode === 200) {
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.currentFileUid) {
                // 获取上传成功的返回地址
                return { url: 'http://' + data.Location, upload: true }
                // upload为true表示这张图片已上传完毕，然后才能保存
              }
              return item
            })
            setTimeout(() => {
              this.showPercent = false
              this.percent = 0
            }, 1000)
          }
        })
      }
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
  display: none
}
</style>
